/* api */
import { checkNotNullForCard, getTaskReviewList, getTaskReviewListInitData, sendReviewMessage, batchAllocateTask } from '@src/api/TaskApi'
/* components */
import BizListViewTask from '@src/component/business/BizListView/Impl/BizListViewTask/BizListViewTask'
/* computed */
import TaskReviewListComputed from '@src/modules/task/taskTypes/review/TaskReviewListComputed'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
import ReviewTypeEnum from '@model/enum/ReviewTypeEnum'
import TaskFlowEnum from '@model/enum/TaskFlowEnum'
import { pageTaskReviewList } from 'pub-bbx-global/pageType/dist'
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum'
/* entity */
import EsTask from '@model/entity/EsTask'
import Field from '@model/entity/Field'
/* model */
import { getColumnFields, getAdvancedFields } from '@src/modules/task/taskTypes/review/fields'
import { getTaskReviewInitDataResult } from '@model/param/out/Task'
import { EvaluateValueEnum, ReviewTypeValueEnum, ReviewValueEnum } from '@src/modules/task/taskTypes/review/TaskReviewListModel'
import { COPY_TEXT_MESSAGE, COPY_TEXT_SUCCESS, COPY_TEXT_FIAL, REVIEW_TASK_SMS_MESSAGE, SEND_SELECTED_REVIEW_TASK_SMS_MESSAGE } from '@src/model/const/Alert'
import { TaskReviewSendSmsModel } from '@model/param/in/Task'
import { commonUseItemType } from '@src/component/AdvancedSearch/advancedSearch'
/* service */
import { isInApprove } from '@service/TaskService'
/* utils */
import { ctiCallOut } from '@src/util/ctisdk';
import Log from '@src/util/log'
import Platform from '@src/util/platform'
import { sessionStorageRemove, sessionStorageGet } from '@src/util/storageV2' 
import { TaskExportReviewFields, TaskExportGroupTextEnum, TaskExportGroupValueEnum, TaskExportEvaluateFields } from '@src/modules/task/taskTypes/review/TaskReviewListModel.ts'
import { allExport } from '@src/modules/task/list/TaskFieldModel'
import { TaskExportGroupChecked } from '@src/component/business/BizListView/Impl/BizListViewTask/BizListViewTaskInterface'
import { TaskExportModel } from '@model/param/in/Task'
import LoginUser from '@model/entity/LoginUser/LoginUser'
import AuthEnum from '@model/enum/AuthEnum'
import { strConcat as concat } from 'pub-bbx-utils'
import { stringify } from '@src/util/lang/object'
import { TaskFieldExportNameMappingEnum, TaskFieldNameMappingEnum } from '@model/enum/FieldMappingEnum'
import TaskApprove from '@model/entity/TaskApprove'
import StorageKeyEnum from '@model/enum/StorageKeyEnum'
import { getFieldName, isNotSupportedDisplayField, isSystemFiled } from '@service/FieldService'
import formatColumn from 'packages/BaseTableCell/formatColumn'
import Column from '@model/types/Column'
import i18n from '@src/locales'
/* hooks */
import { useCopy } from '@hooks/useElement'
import { openSettingSmsmessage } from '@src/util/business/openTab'

import { storageSet, storageGet } from '@src/util/storageV2';

import StorageUtil from '@src/util/storage.ts';
import StorageModuleEnum from '@model/enum/StorageModuleEnum';

class TaskReviewListMethods extends TaskReviewListComputed {

  public computedListPxArray(){
    let com_ = this.$refs.tableComContainer?.offsetHeight || 0;
    let padding = [com_, 24, 16, 16];
    return padding;
  }
  public changePackUpLocal(){
    this.changePackUp()
  }
  /**
   * @description: 获取高级搜索字段列表
   * @param {BizListViewTask} vm 当前实例
   * @return {Field[]} 高级搜索字段列表
   */
  public getAdvancedFields(vm: BizListViewTask): Field[] {
    // 基础版过滤产品、结算人、结算时间、支付方式、曾打印字段
    let advancedFields = getAdvancedFields(vm).filter(field => field.show)
    if (this.isBasicEditionHideProduct) {
      advancedFields = advancedFields.filter(field => field.fieldName !== 'product')
    }
    if (this.isBasicEditionHidePrintTask) {
      advancedFields = advancedFields.filter(field => field.fieldName !== 'oncePrinted')
    }
    if (this.isBasicEditionHidePay) {
      advancedFields = advancedFields.filter(field => field.fieldName !== 'balanceTime' && field.fieldName !== 'paymentMethod' && field.fieldName !== 'balanceUser')

      // 基础版工单状态过滤已结算字段
      advancedFields.forEach(item => {
        if (item.fieldName === 'state') {
          // todo 暂时忽略报错
          // @ts-ignore
          // TODO 国际化待办
          item.setting.dataSource = item.setting?.dataSource.filter((source: string) => source !== '已结算')
        }
      })
    }
    // 是否是人工回访，人工回访去除评价时间搜索
    if(this.isManualReview){
      advancedFields = advancedFields.filter(item => item.fieldName !== 'evaluationTime')
    }
    return advancedFields
  }
  
  /**
   * @description: 获取表格列字段列表
   * @param {BizListViewTask} vm 当前实例
   * @return {Field[]} 表格列字段列表
   */
  public getColumnFields(vm: BizListViewTask): Field[] {
    // 基础版过滤产品、结算人、结算时间、支付方式、曾打印字段
    let columnFields = getColumnFields(vm);
    if (this.isBasicEditionHideProduct) {
      columnFields = columnFields.filter(field => field.fieldName !== 'product')
    }
    if (this.isBasicEditionHidePrintTask) {
      columnFields = columnFields.filter(field => field.fieldName !== 'oncePrinted')
    }
    if (this.isBasicEditionHidePay) {
      columnFields = columnFields.filter(field => field.fieldName !== 'balanceTime' && field.fieldName !== 'paymentMethod' && field.fieldName !== 'balanceUser')
    }

    return columnFields
  }
  
  /** 
   * @description 获取属性
  */
  public getAttributes() {
    const classNames: string[] = [ComponentNameEnum.TaskReviewList, 'common-list-container__v2']
    
    return {
      class: classNames,
      directives: [
        // {
        //   name: 'loading',
        //   value: this.loading
        // }
      ]
    }
  }
  
  /**
   * @description 获取按钮的类型
   * @param {boolean} isSelected 是否选中
   * @return {String} 按钮类型
   */
  public getButtonType(isSelected: boolean): string {
    return isSelected ? 'primary' : 'ghost'
  }
  
  public fetchTableListData() {
    let paramsOther = this.toggleAsignMe();
    const params = {
      ...this.searchParams,
      ...this.advancedSearchModel,
      reviewType: this.reviewType,
      isReview: this.isManualReview ? this.reviewValue : null,
      isEvaluate: this.isAutoReview ? this.evaluateValue : null,
      ...paramsOther,
    }
    this.fetchTaskList(params, getTaskReviewList)
  }
  public taskTypes1 :any = []
  /**
   * @description: 获取初始化数据
   * @return {Promise<void>}
   */
  public async fetchInitData(): Promise<void> {
    this.loading = true
    
    return (
      getTaskReviewListInitData()
        .then(async (result: getTaskReviewInitDataResult) => {
            this.initData = result
            this.taskTypes = result?.taskTypeList || []
            this.taskTypes1 = result?.taskTypeList || []
            this.taskConfig = result?.taskConfig || null
            this.auth = result?.authorities || {}
            this.paymentConfig = result?.paymentConfig || null
            // this.starEvaluates = result?.evaluateConfig?.starEvaluates || []
        })
        .catch(error => {
          Log.error(error, this.fetchInitData.name)
        })
    )
  }
  
  /**
   * @description 是否可以查看当前工单
   * @param {EsTask} task 工单数据
   * @return {Boolean}
   */
  public isCanViewTask(task: EsTask): boolean {
    try {
      return (task?.isReview === 1 && this.isManualReview) || this.isAutoReview
    } catch (error) {
      Log.error(error, this.isCanViewTask.name)
      return false
    }
  }

  /**
   * @description 是否可以发送回访短信当前工单
   * -- 当前为 未评价 且 自动回访 状态下显示
   * @param {EsTask} task 工单数据 
   * @return {Boolean} 
   */
     public isCansendReviewSms(task: EsTask): boolean {
      try {
        return task?.isEvaluated === 0  && this.isAutoReview
      } catch (error) {
        Log.error(error, this.isCansendReviewSms.name)
        return false
      }
    }
  
  /**
   * @description 是否可以回访当前工单
   * -- 当前回访模式为手动回访 且 此工单未回访过 且 不在审批中
   * @param {EsTask} task 工单数据
   * @return {Boolean}
   */
  public isCanReview(task: EsTask): boolean {
    try {
      return (task?.isReview === 0 || task?.isReview === 3) && this.isManualReview && !isInApprove(task)
    } catch (error) {
      Log.error(error, this.isCanViewTask.name)
      return false
    }
  }

  /**
   * @description 是否允许发送回访短信
   * -- 自动回访-未评价状态显示操作按钮
   * @param {EsTask} task 工单数据
   * @return {Boolean}
   */
  public isCanSendReviewSms(task: EsTask): boolean {
    try {
      return this.isAutoReview && this.isUnEvaluate
    } catch (error) {
      Log.error(error, this.isCanViewTask.name)
      return false
    }
  }
  
  /**
   * @description: 初始化工单类型所有字段
   * 工单类型变化之后的事件
   * 1. 获取工单类型字段
   * 2. 获取工单类型回执字段
   * 3. 获取用户开启的配置节点 以及工单搜索范围 和 异常原因字段值
   * 4. 构建高级搜索列
   * @return {void}
   */
  public async initializeTaskTypeAllFields(): Promise<void> {
    // 获取工单类型字段
    await this.fetchTaskFields()
    // 获取工单类型回执字段
    await this.fetchTaskReceiptFields()
    // 获取工单类型问卷字段
    await this.fetchSatisfactionFields()
    // 获取工单类型附加卡片信息
    await this.fetchTaskCardFields()
    // 获取用户开启的配置节点 以及工单搜索范围 和 异常原因字段值
    await this.fetchTurnOnTaskExceptionNodeInfo()
    // 构建高级搜索列
    this.buildAdvancedColumns()
    // 构建导出列
    this.buildExportColumns()
    // 构建选择列
    this.dealWithSelectColumnStorageKey()
  }
  
  public buildSelectColumns() {
    const TaskReceiptFields = this.taskReceiptFields ? this.taskReceiptFields.filter(taskReceiptField => {
      // 是否为系统字段
      const isSystem = isSystemFiled(taskReceiptField)
      // 是否为不支持显示的字段
      const isNotSupportedDisplay = isNotSupportedDisplayField(taskReceiptField)
      
      return !isSystem && !isNotSupportedDisplay
    }) : []

    const SatisfactionFields = this.satisfactionFields ? this.satisfactionFields.filter(satisfactionField => {
      return satisfactionField
    }) : []

    const columnFields = [
      ...this.getColumnFields(this) as Column[],
      ...this.taskFields.filter(field => {
        // 是否为系统字段
        const isSystem = isSystemFiled(field)
        // 是否为不支持显示的字段
        const isNotSupportedDisplay = isNotSupportedDisplayField(field)
        
        return !isSystem && !isNotSupportedDisplay
      }),
      ...TaskReceiptFields,
      ...SatisfactionFields
    ]
    return this.rootWindowInitData?.customerSatisfaction ?
      this.reviewType === 1
      ? columnFields.filter(item => !item.fieldName?.startsWith('eva') && item.fieldName!=='degree'&&item.fieldName!=='evaDegree'&&item.fieldName!=='tagEvaluates') 
      : columnFields.filter(item => item.fieldName !== 'reviewState' && item.fieldName !== 'reviewUser' && item.fieldName !== 'degree' && item.fieldName !== 'reviewTime' && item.fieldName !== 'suggestion' &&item.fieldName!=='evaDegree'&&item.fieldName!=='tagEvaluates')
      :    
      this.reviewType === 1
      ? columnFields.filter(item => !item.fieldName?.startsWith('eva')) 
      : columnFields.filter(item => item.fieldName !== 'reviewState' && item.fieldName !== 'reviewUser' && item.fieldName !== 'degree' && item.fieldName !== 'reviewTime' && item.fieldName !== 'suggestion')
  }

  /**
   * @description 构建高级搜索列
   */
  public buildAdvancedColumns() {
    this.advanceSearchColumns = [
      ...this.getAdvancedFields(this),
    ]
  }
  
  /**
   * @description: 打开回访评价弹窗
   * @return {void}
   */
  public openFeedBackDialog(): void {
    // @ts-ignore
    this.FeedBackDialogComponent?.openDialog()
  }
  
  /**
   * @description 回访工单
   * @return {Promise<void>}
   */
  public async reViewTask(task: EsTask): Promise<void | boolean> {

    this.startLoading()
    this.currentReviewTask = task
    this.readonly = false
    
    try {
      // 检查附加组件是否必填
      const result = await checkNotNullForCard({
        id: this.currentReviewTask?.id,
        flow: TaskFlowEnum.Review
      })
      
      this.endLoading()
      if (!result.succ) return Platform.alert(result.message)
      
      this.openFeedBackDialog()
      
    } catch (error) {
      this.endLoading()
      Log.error(error, this.reViewTask.name)
    }
  }
  
  /**
   * @description 发送回访短信
   * @param {Boolean} task 工单数据，如果有工单数据则只发送当前工单的短信
   * @return {Promise<void>}
   */
  public async sendReviewSms(task?: EsTask): Promise<void> {
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('SEND_REVIEW_MESSAGE', null, 'MORE_ACTIONS'));

    const selectedIds = task ? [task?.id] : this.selectedIds
    const confirmMessage = task ? REVIEW_TASK_SMS_MESSAGE : SEND_SELECTED_REVIEW_TASK_SMS_MESSAGE
    const validated = this.selectedTaskDataValidate(selectedIds)
    
    if (!validated) return
    
    if(task) {
      this.currentEditIds = selectedIds
      this.SendSmsDialogComponent?.openOrCloseDialog(true)
      return
    }
    
    try {
      const confirm = await Platform.confirm(confirmMessage)
      if (!confirm) return
      
      const params: TaskReviewSendSmsModel = {
        type: this.isAutoReview ? ReviewTypeEnum.Auto : ReviewTypeEnum.Manual,
        contentList: selectedIds
      }
      const { message } = await sendReviewMessage(params)

      // @ts-ignore
      this.$track.clickStat(this.$track.formatParams('SEND_REVIEW_MESSAGE_SUCCESS', null, 'MORE_ACTIONS'));
      
      Platform.alert(message)
      
    } catch (error) {
      Log.error(error, this.sendReviewSms.name)
    }
  }

  public closeSmsDialog(): void {
    this.SendSmsDialogComponent?.openOrCloseDialog(false)
    this.currentEditIds = []
  }

  /**
   * @description 切换回访类型
   * @param {ReviewTypeValueEnum} reviewType 回访类型
   * @return {void}
   */
  public toggleReviewType(reviewType: ReviewTypeValueEnum): void {
    this.reviewType = reviewType
    sessionStorage.setItem('reviewType', JSON.stringify(this.reviewType))
    sessionStorage.setItem('reviewValue', JSON.stringify(this.reviewValue))
    sessionStorage.setItem('evaluateValue', JSON.stringify(this.evaluateValue))
    // 构建高级搜索列
    this.buildAdvancedColumns()
    this.dealWithSelectColumnStorageKey()

    this.buildExportColumns()
    this.search()
    this.$nextTick(()=>{
      this.changePackUp();
    })
  }

  public toggleAsignMe() {
    if (!this.isManualReview)  return null;

    if (this.reviewValue === ReviewValueEnum.AssignToMe) {
      return {
        isReview: ReviewValueEnum.All,
        queryType: 2,
      }
    }
  }
  /**
   * @description 切换回访值
   * @param {ReviewValueEnum} reviewValue 回访值
   * @return {void}
   */
  public toggleReviewValue(reviewValue: ReviewValueEnum | any): void {
    this.reviewValue = reviewValue
    sessionStorage.setItem('reviewType', JSON.stringify(this.reviewType))
    sessionStorage.setItem('reviewValue', JSON.stringify(this.reviewValue))
    sessionStorage.setItem('evaluateValue', JSON.stringify(this.evaluateValue))
    
    // 读取对应缓存key 缓存的选择列配置 并render
    this.dealWithSelectColumnStorageKey()

    this.search()
  }

  /**
   * @description 切换评价值
   * @param {ReviewValueEnum} evaluateValue 评价值 
   * @return {void}
   */
  public toggleEvaluateValue(evaluateValue: EvaluateValueEnum): void {
    this.evaluateValue = evaluateValue
    sessionStorage.setItem('reviewType', JSON.stringify(this.reviewType))
    sessionStorage.setItem('reviewValue', JSON.stringify(this.reviewValue))
    sessionStorage.setItem('evaluateValue', JSON.stringify(this.evaluateValue))

    // 读取对应缓存key 缓存的选择列配置 并render
    this.dealWithSelectColumnStorageKey()

    this.search()
  }

  /**
   * @description 查看工单回访信息
   * @param {EsTask} task 工单信息
   * @return {void}
   */
  public viewTask(task: EsTask): void {
    this.currentReviewTask = task
    this.readonly = true

    this.$nextTick(() => {
      this.openFeedBackDialog()
    })
  }

  /**
   * @description: 打开导出面板
   * @param {string} exportIds 导出的ids列表
   * @param {string} fieldName 导出的文件名
   * @return {void}
   */
  public openExportPanel(exportIds: string[], fieldName: string): void {
    // @ts-ignore
    this.BaseExportComponent?.open(exportIds, fieldName)
  }

  /**
  * @description: 构建导出列
  * @return {void}
  */
  public buildExportColumns(): void {
    let columns = allExport.filter((item: any) => 
      item.fieldName !== 'createToCompleteUsedTimeStr' && 
      item.fieldName !== 'inApprove' && 
      item.fieldName !== 'reviewTime' && 
      item.fieldName !== 'source' && 
      item.fieldName !== 'eventNo' && 
      item.fieldName !== 'paymentMethod' 
    )

    // 基础版导出列的系统信息过滤结算人、结算时间、曾打印字段
    if (this.isBasicEditionHidePay) {
      columns = columns.filter((field: any) => field.exportAlias !== 'balanceUser' && field.fieldName !== 'balanceTime')
    }
    if (this.isBasicEditionHidePrintTask) {
      columns = columns.filter((field: any) => field.fieldName !== 'oncePrinted')
    }

    // 基础版导出列的系回执信息过滤备件、服务项目、费用信息字段
    let taskReceiptField = this.buildExportColumnsOfTaskReceiptFields()
    if (this.isBasicEditionHidePart) {
      taskReceiptField = taskReceiptField.filter(field => field.fieldName !== 'spare_name')
    }
    if (this.isBasicEditionHideServe) {
      taskReceiptField = taskReceiptField.filter(field => field.fieldName !== 'service_name')
    }
    if (this.isBasicEditionHidePay) {
      taskReceiptField = taskReceiptField.filter(field => field.fieldName !== 'balance_total')
    }

    this.exportTaskColumns = [
      // 工单字段
      {
        label: TaskExportGroupTextEnum.Task,
        value: TaskExportGroupValueEnum.Task,
        columns: this.buildExportColumnsOfTaskFields()
      },
      // 完成回执字段
      {
        label: TaskExportGroupTextEnum.TaskReceipt,
        value: TaskExportGroupValueEnum.TaskReceipt,
        columns: taskReceiptField
      },
      // 评价信息
      {
        label: TaskExportGroupTextEnum.Evaluate,
        value: TaskExportGroupValueEnum.Evaluate,
        columns: this.buildExportColumnsOfTaskReviewFields()
      },
      // 系统字段
      {
        label: TaskExportGroupTextEnum.System,
        value: TaskExportGroupValueEnum.System,
        columns: this.buildExportColumnsOfTaskReviewSystemFields(columns),
      },
      // 附加卡片字段
      ...this.buildExportColumnsOfTaskCardFields()
    ]
  }

  /**
 * @description: 构建给导出列使用的工单评价信息字段列表
 * @return {Field[]} 给导出列使用的工单评价信息字段列表
 */
  public buildExportColumnsOfTaskReviewFields(): Field[] {
    // const arr = this.initData?.evaluateConfig
    // 评价信息字段列表
    let ExportReviewFields: Field[] = this.isManualReview ? TaskExportReviewFields.slice(0, 5) : TaskExportReviewFields.slice(5);

    let useStarEvaluate: Boolean = this.initData?.evaluateConfig?.useStarEvaluate || false
    let TaskExportStarEvaluatesFields:any = !this.rootWindowInitData?.customerSatisfaction && useStarEvaluate ? this.initData?.evaluateConfig?.starEvaluates.map((item: string, index: number) => {
      return {
        displayName: item,
        fieldName: `starEvaluate${index + 1}`
      }
    }) : this.satisfactionFields ? this.satisfactionFields.filter(satisfactionField => {
      return satisfactionField
    }) : []
    // 服务标签导出控制
    let TaskExportEvaluateFieldsFilter: typeof TaskExportEvaluateFields = TaskExportEvaluateFields.filter((item: (typeof TaskExportEvaluateFields)[number]) => {
      if (item.fieldName === 'tagEvaluates' && !this.initData?.evaluateConfig?.useTagEvaluate) {
        return false
      }
      return true
    })
    ExportReviewFields = [...ExportReviewFields, ...TaskExportStarEvaluatesFields, ...TaskExportEvaluateFieldsFilter];
    ExportReviewFields = this.rootWindowInitData?.customerSatisfaction ? ExportReviewFields.filter(ele => ele.fieldName!=='degree'&&ele.fieldName!=='evaDegree'&&ele.fieldName!=='tagEvaluates') : ExportReviewFields
    return (
      ExportReviewFields.map(field => {
        field.export = true
        field.label = field.displayName
        field.exportAlias = field.fieldName
        return field
      })
    )
  }

  /**
   * @description: 把工单类型值name转换成id
   * @return {void}
   */
   public buildExportColumnsOfTaskReviewSystemFields(columns: any[]) {

    const findIndex = columns.findIndex(f=>f.fieldName == 'createTime')
    const taskUserNameField = {
      fieldName: FieldTypeMappingEnum.TaskUserName,
      exportAlias: FieldTypeMappingEnum.TaskUserName,
      displayName: i18n.t('task.taskTypes.review.assigneeText') as string,
    }
    columns.splice(findIndex,0, taskUserNameField) 
    
    return columns.map((field: any) => ({
      ...field,
      export: true,
      label: field.displayName || '',
    }));
  }

  /**
   * @description: 把工单类型值name转换成id
   * @return {void}
   */
  public templateNameConversion(): void {
    if (Array.isArray(this.taskType)) {
      const row = this.taskType.find((item: { name: any }) => item.name === this.searchParams.templateName)
      this.searchParams.templateName = row?.id;
    }
  }

  /**
   * @description 构建导出参数
   * @return {Object} 导出参数
   */
  public buildExportParams(checkedMap: TaskExportGroupChecked, ids: string[], exportOneRow?: boolean): TaskExportModel {
    let paramsOther = this.toggleAsignMe();

    let { receiptChecked = [], systemChecked = [], taskChecked = [], evaluateChecked = [] } = checkedMap
    // 登录用户信息
    const loginUser: LoginUser | undefined = this.rootWindowInitData?.user
    // 是否为导出全部
    const isExportAll: boolean = Boolean(!ids || !ids?.length)
    // 导出需要的搜索参数模型
    const exportSearchModel: Record<string, any> = {
      ...this.searchParams,
      ...this.advancedSearchModel,
      // 工单ids
      taskIds: isExportAll ? [] : this.selectedIds,
      // 当前登录人的团队列表
      tagIds: loginUser?.tagList?.map(tag => tag.id) || [],
      // 数据权限等级
      dataLevel: this.auth[AuthEnum.TASK_VIEW],
      // 租户id
      tenantId: loginUser?.tenantId,
      // 导出的数量
      exportTotal: isExportAll ? this.page.totalElements : this.selectedIds.length,
      reviewType: this.reviewType,
      isReview: this.isManualReview ? this.reviewValue : null,
      isEvaluate: this.isAutoReview ? this.evaluateValue : null,
      ...paramsOther,
    }
    
    // 关联表单和服务商的过滤
    if(this.taskFields.some(item => item.formType === 'relationForm' || item.formType === 'serviceProviders')){
      const fieldNameList = this.taskFields.filter(item => item.formType === 'relationForm' || item.formType === 'serviceProviders').map(item => item.fieldName);
      fieldNameList.forEach(item => {
        taskChecked = taskChecked.filter(val => val !== item)
      })
    }
    return {
      cardFieldChecked: this.buildExportParamsOfCardFieldChecked(checkedMap),
      checked: this.buildExportParamsOfChecked(taskChecked),
      data: isExportAll ? '' : concat(this.selectedIds),
      exportOneRow: Boolean(exportOneRow),
      exportSearchModel: stringify(exportSearchModel),
      receiptChecked: this.buildExportParamsOfReceiptChecked(receiptChecked),
      sysChecked: this.buildExportParamsOfSystemChecked(systemChecked),
      typeId: this.currentTaskType?.id || '',
      evaluateChecked: this.buildExportParamsOfEvaluateChecked(evaluateChecked),
      reviewType: this.reviewType,
      isReview: this.isManualReview ? this.reviewValue : null,
      isEvaluate: this.isAutoReview ? this.evaluateValue : null,
      ...paramsOther,
    }
  }

  /**
   * @description 构建导出参数-工单附件组件字段选择的参数
   * @return {Sintrg[]} 附件组件字段选择的数据 
   */
  private buildExportParamsOfCardFieldChecked(checkedMap: TaskExportGroupChecked): string {
    let cardFieldChecked: string[] = []
    
    for (let key in checkedMap) {
      if (key.indexOf(TaskExportGroupValueEnum.Card) !== -1) {
        cardFieldChecked = [...cardFieldChecked, ...checkedMap[key]]
        if(checkedMap[key].length > 0) {
          this.exportTaskColumns.forEach(item => {
            if(item.value == key) {
              cardFieldChecked = [...cardFieldChecked, item.cardId]
            }
          });
        }
      }
    }
    
    cardFieldChecked = cardFieldChecked.length ? this.exportDatas(3, cardFieldChecked) : cardFieldChecked
    
    return concat(cardFieldChecked)
  }

  /**
   * @description 构建导出参数-工单字段选择的参数
   * @return {Sintrg[]} 工单字段字段选择的数据
   */
  private buildExportParamsOfChecked(taskChecked: string[]): string {
    let exportTaskChecked: string[] = this.exportDatas(0, taskChecked)
    
    exportTaskChecked = exportTaskChecked
      .map((checkedKey: string) => {
        
        // 产品特殊处理 (添加产品编号字段)
        if (checkedKey === TaskFieldNameMappingEnum.Product) {
          checkedKey = concat([
            TaskFieldNameMappingEnum.Product,
            TaskFieldNameMappingEnum.ProductSN
          ])
        }
        
        return checkedKey
      })
    
    return concat(exportTaskChecked)
  }

  /**
   * @description 构建导出参数-工单回执字段选择的参数
   * @return {Sintrg[]} 工单回执字段字段选择的数据
   */
  private buildExportParamsOfReceiptChecked(taskReceiptChecked: string[]): string {
    let exportTaskReceiptChecked: string[] = this.exportDatas(1, taskReceiptChecked)
    
    exportTaskReceiptChecked = exportTaskReceiptChecked
      .map((checkedKey: string) => {
        
        // 如果选择【备件名称】列，则手动补全其他备件列数据
        if (checkedKey === TaskFieldExportNameMappingEnum.SparePartName) {
          checkedKey = concat([
            TaskFieldExportNameMappingEnum.SparePartName,
            TaskFieldExportNameMappingEnum.SparePartSN,
            TaskFieldExportNameMappingEnum.SparePartType,
            TaskFieldExportNameMappingEnum.SparePartStandard,
            TaskFieldExportNameMappingEnum.SparePartNumber,
            TaskFieldExportNameMappingEnum.SparePartCost
          ])
        }
        
        // 如果选择【服务项目】列，则手动补全其他服务项目列数据
        if (checkedKey === TaskFieldExportNameMappingEnum.ServiceName) {
          checkedKey = concat([
            TaskFieldExportNameMappingEnum.ServiceName,
            TaskFieldExportNameMappingEnum.ServiceType,
            TaskFieldExportNameMappingEnum.ServiceNumber,
            TaskFieldExportNameMappingEnum.ServiceCost
          ])
        }
        
        // 如果选择【费用信息】列，则手动补全其他结算费用列数据
        if (checkedKey === TaskFieldExportNameMappingEnum.BalanceTotal) {
          checkedKey = concat([
            TaskFieldExportNameMappingEnum.BalanceTotal,
            TaskFieldExportNameMappingEnum.BalanceDiscount,
            TaskFieldExportNameMappingEnum.BalanceSum
          ])
        }
        
        return checkedKey
      })
    
    return concat(exportTaskReceiptChecked)
  }

  /**
   * @description 构建导出参数-工单系统字段选择的参数
   * @return {Sintrg[]} 工单系统字段字段选择的数据
   */
  private buildExportParamsOfSystemChecked(systemChecked: string[]): string {
    const exportTaskSystemChecked: string[] = this.exportDatas(3, systemChecked)
    
    return concat(exportTaskSystemChecked)
  }

  /**
   * @description 构建导出参数-工单系统字段选择的参数
   * @return {Sintrg[]} 工单系统字段字段选择的数据
   */
  private buildExportParamsOfEvaluateChecked(evaluateChecked: string[]): string {
    const exportTaskEvaluateChecked: string[] = this.exportDatas(2, evaluateChecked)
    return concat(exportTaskEvaluateChecked)
  }
  
  private exportDatas(number: number, list: any[] = []) {
    const export_list = this.exportTaskColumns
    
    if (number === 3) {
      let cardField: any[] = []
      export_list.filter((item, index) => {
        return index > 2
      }).forEach(v => {
        v.columns.forEach(item => {
          cardField.push(item)
        })
      })
      let cardIdArr:any[] = []
      let cardFieldArr = cardField.map(v => {
        let bool = list.some(item => {
          // 附加组件需要加一个新的参数cardId_${cardId}, 暂时先这么改
          if( v.cardIdExp == item ) cardIdArr.push(v.cardIdExp)
          if (v.exportAlias) {
            return v.exportAlias === item
          } 
          return v.fieldName === item
          
        })
        if (bool) {
          return v.exportAlias ? v.exportAlias : v.fieldName
        }
      }).filter(item => {
        return item
      })
      cardIdArr = [...new Set(cardIdArr)];
      cardFieldArr = [...cardFieldArr, ...cardIdArr]
      return cardFieldArr
    }
    
    return export_list[number].columns.map(v => {
      let bool = list.some(item => {
        if (v.exportAlias) {
          return v.exportAlias === item
        } 
        return v.fieldName === item
        
      })
      if (bool) {
        return v.exportAlias ? v.exportAlias : v.fieldName
      }
    }).filter(item => {
      return item
    })
  }

  /**
   * @description 打开审批弹窗
   * @param {*} data
   * @return {void}
   */  
  public proposeApprove(approveData: TaskApprove): void {
    // @ts-ignore
    this.ProposeApproveDialogComponent?.openDialog(approveData)
  }

  /**
   * @description: 根据结算状态变化改变审核结算selectColumnStorageKey，获取columns配置并且render表格
   * @return {void}
   */  
  private dealWithSelectColumnStorageKey(): void {
    // 不同tab赋值不同的缓存key
    this.selectColumnStorageKey = this.formatReviewStorageKey()

    const columns = this.buildSelectColumns()
    // 构建列数据
    this.columns = [...columns].map(field => {
      return {
        ...formatColumn(field),
        field: getFieldName(field)
      }
    })
    
    // 合并本地缓存列数据至当前实例的列数据
    this.mergeLocalStorageColumnsToColumns()
  }

  // 不同tab赋值不同的缓存key
  private formatReviewStorageKey() {
    let storageKey:StorageKeyEnum = StorageKeyEnum.TaskReviewTableColumnsAutoNot
    if(this.reviewType === 1) { // 人工
      if(this.reviewValue === 0) {
        storageKey = StorageKeyEnum.TaskReviewTableColumnsManualNot // 人工回访-未回访
      } else if(this.reviewValue === 1) {
        storageKey = StorageKeyEnum.TaskReviewTableColumnsManualDone // 人工回访-已回访
      } else if(this.reviewValue === 2) {
        storageKey = StorageKeyEnum.TaskReviewTableColumnsManualAll // 人工回访-全部
      }
    } else if(this.reviewType === 2) { // 自动
      if(this.evaluateValue === 0) {
        storageKey = StorageKeyEnum.TaskReviewTableColumnsAutoNot // 自动回访-未评价
      } else if(this.evaluateValue === 1) {
        storageKey = StorageKeyEnum.TaskReviewTableColumnsAutoDone // 自动回访-已评价
      } else if(this.evaluateValue === 2) {
        storageKey = StorageKeyEnum.TaskReviewTableColumnsAutoAll // 自动回访-全部
      }
    }
    return storageKey
  }

  /**
   * @description 刷新页面读取缓存
   */
  public refreshTask() {
    const reviewType:any = sessionStorage.getItem('reviewType')

    if (reviewType === '1') {
      this.reviewType = JSON.parse(reviewType)
      const reviewValue:any = sessionStorage.getItem('reviewValue');
      this.reviewValue = JSON.parse(reviewValue)
    } else if (reviewType === '2') {
      this.reviewType = JSON.parse(reviewType)
      const evaluateValue:any = sessionStorage.getItem('evaluateValue');
      this.evaluateValue = JSON.parse(evaluateValue)
    }
  }
  

  public refresh() {
    this.loading = true
    setTimeout(async () => {
      this.BizTableComponent?.outsideClearSelection()
      this.multipleSelection = []
      await this.search()
      // this.loading = false
    }, 1000)
  }


  // 处理未接来电打电话
  public async makePhoneCall(tel:string){
    if(!tel) return
    try {
      ctiCallOut(tel)
    } catch (error) {
      console.error(error);
    }
  }

  /**
   *复制
   */
  public copyGuideText(reviewValue: ReviewValueEnum): void {
    useCopy(COPY_TEXT_MESSAGE, COPY_TEXT_SUCCESS, COPY_TEXT_FIAL)
  }  
  public toSetMessage(): void {
    openSettingSmsmessage()
  }
  
  /**
   * @des 提供给快捷筛选视图的方法
   */
   public fasterFilterList(keyObj:any){
    try {
      let arr_ = [];
      for(let key in keyObj){
        // All 全部 Reviewed 已回访 UnReview 未回访 FollowUp 跟进中
        let value = keyObj[key]
        if(key == 'toggleReviewValue'){
          // 指向function toggleReviewValue
          let val_ = ReviewValueEnum[value]
          this.toggleReviewValue(val_)
        }
      }
      // this.search();
    } catch (error) {
      console.warn(error, 'fasterFilterList error try catch');
    }
  }
  /**
   * @des 查询是否有查询参数
   */
  public findFastPageData(data?:any){
    return new Promise((resolve:any, reject)=>{
      try {
        let parseData = sessionStorageGet(`bbx-faster-${pageTaskReviewList.type}`);
        if(parseData){
          sessionStorageRemove(`bbx-faster-${pageTaskReviewList.type}`);
        }
        if(!data && !parseData) return resolve()
        const {filterData} = data || JSON.parse(parseData);
        this.fasterFilterList(filterData);
        
      } catch (error) {
        console.warn(error, 'findFastPageData error try catch');
        resolve()
      }
    })
  }

  /**
   * 高级搜索
   * @param searchModel
   */
  public handleAdvancedSearch(searchModel: any = {}){
    this.advancedSearchModel = searchModel;
    this.search();
  }

  /**
   * 常用字段切换
   * @param {*} fieldName
   * @param {*} isChecked
   */
  public changeCommonUse({fieldName, isChecked}: commonUseItemType){
    const inCommonUseSet = new Set(this.inCommonUse)
    if(isChecked){
      inCommonUseSet.add(fieldName)
    }else {
      inCommonUseSet.delete(fieldName);
    }
    this.inCommonUse = Array.from(inCommonUseSet);
    try {
      StorageUtil.storageSet(this.advancedSearchFieldStorageKey, this.inCommonUse, StorageModuleEnum.Task)
    } catch (error) {
      console.error('changeCommonUse ~ setIndexedDbData ~ error', error)
    }
  }

  /**
   * 恢复常用字段
   */
  public async recoverCommonUse(){
    try {
      this.inCommonUse = await StorageUtil.storageGet(this.advancedSearchFieldStorageKey, [], StorageModuleEnum.Task)
    } catch (error) {
      console.error('获取常用字段 recoverCommonUse', error);
      return Promise.reject(error)
    }
  }

  /*批量指派*/
  public batchAssignment() {
    if (this.selectedIds.length <= 0) return this.$message.warning(i18n.t('task.taskTypes.review.assignToMeMsg1'));

    let options = {
      title: i18n.t('task.taskTypes.review.assignToMeMsg2'),
      selectedUsers: null,
      max: 1,
      unique: false,
      haveRole: true,
      showServiceProvider: false,
      showRole: false,
      showDelete: false,
    };
    // @ts-ignore
    this.$fast.select.multi.user(options)
      .then((result: any) => {
        let userId = result?.data?.all[0]?.userId
        batchAllocateTask({taskIds: this.selectedIds, userId})
          .then((res) => {
            this.$message({
              type: res.success ? 'success' : 'error',
              message: res.success ? i18n.t('task.taskTypes.review.assignToMeMsg3') : res.message,
            })
            this.search()
          })
          .catch((err) => {
            console.error(err)
          })
      })
      .catch((err: any) => {
        console.error(err)
      })
  }
}

export default TaskReviewListMethods
